package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.GoalRequest;
import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.entity.GoalItem;
import com.ruoyi.livedemo.mapper.GoalItemMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class GoalService {

    private final GoalItemMapper goalItemMapper;

    public PagedResult<GoalItem> list(Long userId, String status, String category, int page, int size) {
        int pageSize = size <= 0 ? 10 : size;
        int currentPage = Math.max(page, 0);
        int offset = currentPage * pageSize;
        List<GoalItem> items = goalItemMapper.findPage(userId, status, category, offset, pageSize);
        long total = goalItemMapper.count(userId, status, category);
        return new PagedResult<>(total, items);
    }

    @Transactional
    public GoalItem create(Long userId, GoalRequest request) {
        GoalItem item = new GoalItem();
        item.setUserId(userId);
        item.setTitle(request.getTitle());
        item.setDescription(request.getDescription());
        item.setTargetDate(request.getTargetDate());
        item.setStatus(StringUtils.hasText(request.getStatus()) ? request.getStatus() : "PENDING");
        item.setProgressRatio(request.getProgressRatio() != null ? request.getProgressRatio() : 0);
        item.setCategory(request.getCategory());
        item.setCoverPath(request.getCoverPath());
        goalItemMapper.insert(item);
        return item;
    }

    @Transactional
    public GoalItem update(Long userId, Long id, GoalRequest request) {
        GoalItem existing = goalItemMapper.findByIdAndUser(id, userId);
        if (existing == null) {
            throw new IllegalArgumentException("未找到目标");
        }
        existing.setTitle(request.getTitle());
        existing.setDescription(request.getDescription());
        existing.setTargetDate(request.getTargetDate());
        if (StringUtils.hasText(request.getStatus())) {
            existing.setStatus(request.getStatus());
        }
        if (request.getProgressRatio() != null) {
            existing.setProgressRatio(request.getProgressRatio());
        }
        existing.setCategory(request.getCategory());
        existing.setCoverPath(request.getCoverPath());
        goalItemMapper.update(existing);
        return existing;
    }

    @Transactional
    public void delete(Long userId, Long id) {
        goalItemMapper.delete(id, userId);
    }
}
